﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;

namespace matrixdotnet.Common
{
    public class ByTypeRegistry
    {
        private Dictionary<Type, object> _registry = new Dictionary<Type, object>();

        public T GetObject<T>()
        {
            object obj = null;

            if (_registry.TryGetValue(typeof(T), out obj))
                return (T)obj;

            return (T)CreateObject<T>();
        }

        private object CreateObject<T>()
        {
            IDictionary dict =
                (IDictionary)ConfigurationManager.GetSection("typeRegistryBindings");
            if (dict == null)
                return null;

            string requestedType = typeof(T).ToString();
            if (!dict.Contains(requestedType))
                return null;
            string realTypeKey = (string)dict[requestedType];

            dict = (IDictionary)ConfigurationManager.GetSection("typeRegistry");
            if (dict == null)
                return null;

            if (!dict.Contains(realTypeKey))
                return null;
            string realType = (string)dict[realTypeKey];

            return Activator.CreateInstance(Type.GetType(realType));
        }
    }
}
